package com.steven.ourcontest.login.view

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.widget.Toast
import androidx.activity.viewModels
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import com.gyf.immersionbar.ImmersionBar
import com.steven.ourcontest.R
import com.steven.ourcontest.base.BaseActivity
import com.steven.ourcontest.login.helper.LoginController
import com.steven.ourcontest.login.helper.LoginController.CODE_TIME
import com.steven.ourcontest.login.viewmodel.LoginViewModel
import com.steven.ourcontest.utils.changed
import com.steven.ourcontest.utils.toast
import kotlinx.android.synthetic.main.activity_login.*
import kotlin.math.abs

class LoginActivity : BaseActivity() {

    private var status = 1 //1登录状态  2注册状态
    private var quick = false
    private var getCode = false
    private var email: String = ""
    private val loginViewModel: LoginViewModel by viewModels()
    private val regex = Regex("^[A-Za-z0-9.\\u4e00-\\u9fa5]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+\$")

    override fun getViewId(): Int? {
        return R.layout.activity_login
    }

    override fun getStatusBarColor(): Int {
        return R.color.white
    }

    override fun initView() {

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initListener()
    }

    private fun initListener() {
        bt_get_code?.setOnClickListener {
            if (email == "") {
                toast("邮箱不能为空！")
                return@setOnClickListener
            }
            if (!email.matches(regex)) {
                toast("邮箱错误！")
                return@setOnClickListener
            }
            bt_get_code.initKeeper(60000, "秒后重获")
            bt_get_code.start {
                loginViewModel.sendCode(email)
                LoginController.lastSendCodeTime = System.currentTimeMillis()
            }
            getCode = true
        }
        tv_login?.setOnClickListener {
            login()
        }
        tv_register?.setOnClickListener {
            register()
        }
        rl_quick?.setOnClickListener {
            quickLogin()
        }
        iv_next?.setOnClickListener {
            if (quick) {
                //验证码30分钟过期
                if (abs(LoginController.lastSendCodeTime - System.currentTimeMillis()) <= CODE_TIME) {
                    //校验用户是否修改邮箱
                    if (email == loginViewModel.lastSendCodeEmail) {
                        if (et_code_quick_login?.text.toString() == LoginController.lastSendCode.toString()) {
                            loginViewModel.quickLogin(email)
                        } else {
                            toast("验证码错误！")
                        }
                    } else {
                        toast("请输入获取验证码的邮箱！")
                    }
                } else {
                    Toast.makeText(this, "验证码已过期，请重新获取", Toast.LENGTH_SHORT).show()
                }
            } else {
                when (status) {
                    1 -> {
                        if (email != "" && et_pwd_login?.text.toString() != "") {
                            loginViewModel.login(email, et_pwd_login?.text.toString())
                        } else {
                            Toast.makeText(this, "邮箱和密码不能为空！", Toast.LENGTH_SHORT).show()
                        }
                    }
                    2 -> {
                        //验证码30分钟过期
                        if (abs(LoginController.lastSendCodeTime - System.currentTimeMillis()) <= CODE_TIME) {
                            if (email != loginViewModel.lastSendCodeEmail) {
                                toast("请输入获取验证码的邮箱！")
                                return@setOnClickListener
                            }
                            if (et_code?.text.toString() != LoginController.lastSendCode.toString()) {
                                toast("验证码错误！")
                                return@setOnClickListener
                            }
                            if (email != "" && et_pwd_logon?.text.toString() != "" && et_confirm_pwd_logon?.text.toString() != "") {
                                if (et_pwd_logon?.text.toString() == et_confirm_pwd_logon?.text.toString()) {
                                    loginViewModel.signUp(email, et_pwd_logon?.text.toString())
                                } else {
                                    toast("两次密码输入不一致！")
                                }
                            } else {
                                toast("邮箱和密码不能为空！")
                            }
                        } else {
                            toast("验证码已过期，请重新获取")
                        }
                    }
                }
            }
        }
        et_email_login?.changed {
            email = et_email_login?.text.toString()
        }
        et_email_register?.changed {
            email = et_email_register?.text.toString()
        }
        et_email_quick_login?.changed {
            email = et_email_quick_login?.text.toString()
        }
        loginViewModel.loginResponse.observe(this, Observer {
            if (it?.canLogin == true) {
                loginSuccess(it.userId)
            } else {
                Toast.makeText(this, it?.msg, Toast.LENGTH_SHORT).show()
            }
        })
        loginViewModel.signUpResponse.observe(this, Observer {
            if (it?.canSignUp == true) {
                loginSuccess(it.userId)
            } else {
                Toast.makeText(this, it?.msg, Toast.LENGTH_SHORT).show()
            }
        })
    }

    private fun login() {
        if (status == 2) {
            rl_regular_sign_up?.isVisible = false
            rl_regular_login?.isVisible = true
            tv_register?.setBackgroundResource(R.drawable.shape_background_empty)
            tv_login?.setBackgroundResource(R.drawable.shape_bottom_frame)
            codeDisappear()
            status = 1
            et_email_login?.setText(email)
        }
    }

    private fun register() {
        if (status == 1) {
            rl_regular_sign_up?.isVisible = true
            rl_regular_login?.isVisible = false
            tv_login?.setBackgroundResource(R.drawable.shape_background_empty)
            tv_register?.setBackgroundResource(R.drawable.shape_bottom_frame)
            codeAppears()
            status = 2
            et_email_register?.setText(email)
        }
    }

    private fun quickLogin() {
        if (!quick) {
            codeAppears()
            rl_quick?.isVisible = false
            rl_quick_card?.isVisible = true
            rl_regular_card?.isVisible = false
            quick = true
            et_email_quick_login?.setText(email)
        }
    }

    private fun codeAppears() {
        bt_get_code?.isVisible = true
    }

    private fun codeDisappear() {
        bt_get_code?.isVisible = false
    }

    private fun loginSuccess(userId: Long) {
        LoginController.isLogin = true
        LoginController.userId = userId
        val intent = Intent()
        intent.putExtra("action", "loginSuccess")
        setResult(100, intent)
        finish()
    }

    override fun onBackPressed() {
        if (quick) {
            rl_quick?.isVisible = true
            rl_quick_card?.isVisible = false
            rl_regular_card?.isVisible = true
            quick = false
            codeDisappear()
            return
        }
        super.onBackPressed()
    }
}